﻿Imports System.Data
Partial Class WebForm_CustomerGroupPercentage
    Inherits System.Web.UI.Page
    Dim lManager As New LevelManager

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.BindDDLDivision()
            Me.BindDDLSignature()
            Me.BindDDLLevel2Name()
            Me.InitDataAndShow()
        End If
    End Sub

    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click
        Me.InitDataAndShow()
    End Sub

    Protected Sub ddlDivision_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlDivision.SelectedIndexChanged
        Me.BindDDLSignature()
        Me.BindDDLLevel2Name()
    End Sub

    Protected Sub ddlSignature_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlSignature.SelectedIndexChanged
        Me.BindDDLLevel2Name()
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim SumValue As Decimal = 0
        Dim sPercentage As String
        Dim pValue As Decimal
        '驗證是否總和為100%
        For i As Integer = 0 To Me.gv.Rows.Count - 1
            sPercentage = TryCast(Me.gv.Rows(i).FindControl("txtPercentage"), TextBox).Text
            If Decimal.TryParse(sPercentage, pValue) Then
                SumValue += pValue
            End If
        Next

        '驗證通過則寫入資料
        If SumValue <> 100 Then
            MyObj.ShowMessage(Me.GetLocalResourceObject("AlertMessage") & " (" & SumValue & "%)")
        Else
            Dim sSignature, sChannel, sLevel2Name, sLevel2Value As String
            Dim cuser As String = clsAuth.GetUserID()
            Dim dat As New clsData
            Dim sql As New MyStringBuilder
            For i As Integer = 0 To Me.gv.Rows.Count - 1
                sPercentage = TryCast(Me.gv.Rows(i).FindControl("txtPercentage"), TextBox).Text
                If Decimal.TryParse(sPercentage, pValue) Then
                    sSignature = Me.gv.DataKeys(i).Item("Signature").ToString()
                    sChannel = Me.gv.DataKeys(i).Item("Channel").ToString()
                    sLevel2Value = Me.gv.DataKeys(i).Item("Level2Value").ToString()
                    If sLevel2Value <> "" Then
                        sLevel2Name = Me.Level2Name
                    Else
                        sLevel2Name = ""
                    End If

                    sql.Length = 0
                    Dim dt As DataTable
                    sql.AppendFormat("SELECT * FROM ChannelPercentage ")
                    sql.AppendFormat("WHERE Signature ='{0}' AND Channel='{1}' ", sSignature, sChannel)
                    sql.AppendFormat("AND Level2Name ='{0}' ", sLevel2Name)
                    sql.AppendFormat("AND Level2Value ='{0}' ", sLevel2Value)
                    dt = dat.GetData(sql.ToString())

                    sql.Length = 0
                    If (dt.Rows.Count > 0) Then
                        'Update
                        sql.AppendFormat(" UPDATE ChannelPercentage SET Percentage ={0}, UpdateBy='{1}', UPdateDate='{2:yyyy/MM/dd}'", pValue, cuser, DateTime.Now)
                        sql.AppendFormat(" WHERE 1=1 ")
                        sql.AppendFormat(" AND Signature ='{0}'", sSignature)
                        sql.AppendFormat(" AND Channel ='{0}'", sChannel)
                        sql.AppendFormat(" AND Level2Name ='{0}' ", sLevel2Name)
                        sql.AppendFormat(" AND Level2Value ='{0}' ", sLevel2Value)
                        dat.AccData(sql.ToString)
                    Else
                        'Insert
                        sql.AppendFormat(" INSERT ChannelPercentage(Signature,Level2Name,Level2Value,Channel,Percentage,CreateBy,CreateDate) ")
                        sql.AppendFormat(" Select ")
                        sql.AppendFormat(" '{0}' ", sSignature)
                        sql.AppendFormat(" ,'{0}' ", sLevel2Name)
                        sql.AppendFormat(" ,'{0}' ", sLevel2Value)
                        sql.AppendFormat(" ,'{0}' ", sChannel)
                        sql.AppendFormat(" ,{0} ", pValue)
                        sql.AppendFormat(" ,'{0}' ", cuser)
                        sql.AppendFormat(" ,'{0:yyyy/MM/dd}' ", DateTime.Now)
                        dat.AccData(sql.ToString)
                    End If
                End If
            Next
            MyObj.ShowMessage(Me.GetLocalResourceObject("SaveDone"))
        End If
    End Sub

#Region "Gridview事件"
    Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv.PageIndexChanging
        Me.gv.PageIndex = e.NewPageIndex
        Me.InitDataAndShow()
    End Sub

    Protected Sub gv_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gv.PageIndexChanged
        InitDataAndShow()
    End Sub

    Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            'Dim oRow As Data.DataRowView
            'oRow = CType(e.Row.DataItem, Data.DataRowView)

            'e.Row.Cells(6).Text = oRow("Percentage") + "%"
        End If
    End Sub
    Protected Sub gv_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gv.RowEditing
        gv.EditIndex = e.NewEditIndex
        InitDataAndShow()
    End Sub

    Protected Sub gv_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles gv.RowCancelingEdit
        gv.EditIndex = -1
        InitDataAndShow()
    End Sub

    Protected Sub gv_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gv.RowUpdating
        'SAVE
        Dim cuser As String
        cuser = clsAuth.GetUserID()

        Dim sSignature As String
        Dim sChannel As String
        Dim sPercentage As String
        sSignature = gv.DataKeys(e.RowIndex).Values("Signature")
        sChannel = gv.DataKeys(e.RowIndex).Values("Channel")
        'sPercentage = e.NewValues("Percentage")
        sPercentage = DirectCast(gv.Rows(e.RowIndex).FindControl("txtPercentage"), TextBox).Text.Replace("%", "")

        If Not IsNumeric(sPercentage) Then
            MyObj.ShowMessage("Please input Numeric !!")
            Return
        Else

            Dim dtPercentage As DataTable = CType(ViewState("dtPercentage"), DataTable)
            Dim dv As DataView
            '如果Division選擇ALL時，與編緝資料列的Division做篩選
            If ddlDivision.SelectedValue = "" Then
                dv = dtPercentage.DefaultView
                dv.RowFilter = String.Format("Signature='{0}'", sSignature)
                dtPercentage = dv.ToTable
            End If
            Dim dtOld As DataTable
            dv = dtPercentage.DefaultView
            dv.RowFilter = String.Format("Signature='{0}' AND Channel='{1}'", sSignature, sChannel)
            dtOld = dv.ToTable

            '編輯前的值
            Dim oldValue As String = dtOld.Rows(0)("Percentage").ToString.Replace("%", "")
            If oldValue = "" Then oldValue = 0
            '扣除編輯前的值
            Dim SumValue As String = dtPercentage.Compute("Sum(iPercentage)", "").ToString()
            If SumValue = "" Then SumValue = 0
            If (SumValue - CLng(oldValue)) + CLng(sPercentage) > 100 Then
                MyObj.ShowMessage("Signature Total no larger than 100 !!")
                Return
            End If
        End If

        Dim dat As New clsData
        Dim dt As DataTable = dat.GetData(String.Format(" SELECT * FROM ChannelPercentage WHERE Signature ='{0}' AND Channel='{1}' ", sSignature, sChannel))

        Dim sql As New MyStringBuilder

        If (dt.Rows.Count > 0) Then
            'Update
            sql.AppendFormat(" UPDATE ChannelPercentage SET Percentage ={0}, UpdateBy='{1}', UPdateDate='{2:yyyy/MM/dd}'", sPercentage, cuser, DateTime.Now)
            sql.AppendFormat(" WHERE 1=1 ")
            sql.AppendFormat(" AND Signature ='{0}'", sSignature)
            sql.AppendFormat(" AND Channel ='{0}'", sChannel)
            dat.AccData(sql.ToString)
        Else
            'Insert
            sql.AppendFormat(" INSERT ChannelPercentage ")
            sql.AppendFormat(" SELECT '{0}','{1}',{2},'{3}','{4:yyyy/MM/dd}','{5}','{6:yyyy/MM/dd}' ", sSignature, sChannel, sPercentage, cuser, DateTime.Now, cuser, DateTime.Now)
            dat.AccData(sql.ToString)
        End If

        gv.EditIndex = -1
        InitDataAndShow()

    End Sub
#End Region

#Region "繫結資料"
    Private Sub BindDDLDivision()
        Dim ddlControl As DropDownList = Me.ddlDivision
        Dim dvManager As New DivisionManager

        ddlControl.DataTextField = "Division"
        ddlControl.DataValueField = "Division"
        ddlControl.DataSource = dvManager.GetAllDivision()
        ddlControl.DataBind()
        'ddlControl.Items.Insert(0, MyObj.GetDDLSelectAllItem())
    End Sub

    Private Sub BindDDLSignature()
        Dim ddlControl As DropDownList = Me.ddlSignature
        Dim stManager As New SignatureManager

        ddlControl.DataTextField = "Description"
        ddlControl.DataValueField = "Signature"
        ddlControl.DataSource = stManager.GetSignatureNoNewCategories(Me.ddlDivision.SelectedValue)
        ddlControl.DataBind()
        'ddlControl.Items.Insert(0, MyObj.GetDDLSelectAllItem())
    End Sub

    Private Sub BindDDLLevel2Name()
        Dim ddlControl As DropDownList = Me.ddlLevel2Name

        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As New DataTable
        Me.IsChain = "Y"

        sql.Length = 0
        sql.AppendFormat("  Select Top 1 * from  ")
        sql.AppendFormat("  ( ")
        sql.AppendFormat("    select top 2 A.HierarchyName,A.Sequence,B.Chain from MaintainLevel A join ProductLevel B on A.HierarchyName=B.LevelName ")
        sql.AppendFormat("    where A.ViewPoint='SF' ")
        sql.AppendFormat("    and A.Division='{0}' and A.IsSelect='Y' order by A.Sequence ", Me.ddlDivision.SelectedValue)
        sql.AppendFormat("  )A order by A.Sequence desc ")
        dt = dat.GetData(sql.ToString())
        If dt.Rows.Count > 0 Then
            Me.Level2Name = dt.Rows(0)("HierarchyName").ToString()
            Me.IsChain = dt.Rows(0)("Chain").ToString()
        Else
            Me.Level2Name = ""
        End If

        sql.Length = 0
        sql.AppendFormat("Select distinct Description ")
        If Me.IsChain = "Y" Then
            sql.AppendFormat(",code ")
        Else
            Dim hmManager As New HierarchyManager
            sql.AppendFormat(",substring(code,{0}*2-1,2) as code ", hmManager.GetSequence(Me.Level2Name))
        End If
        sql.AppendFormat("from ProductHierarchyOriginal ")
        sql.AppendFormat("where LevelName ='{0}' ", Me.Level2Name)
        sql.AppendFormat("and Left(code,2)='{0}' And Active='Y' ", Left(Me.ddlSignature.SelectedValue, 2))
        If MyObj.IsCatagory(Me.ddlSignature.SelectedItem.Text) Then
            If Me.IsChain = "Y" Then
                sql.AppendFormat("AND code in ")
            Else
                sql.AppendFormat("AND substring(code,{0}*2-1,2) in ")
            End If
            sql.AppendFormat("({0}) ", MyObj.JoinFormat(",", "'{0}'", lManager.GetItemCodes(Me.ddlDivision.SelectedValue, Me.Level2Name, Me.ddlSignature.SelectedItem.Text)))
        End If

        sql.AppendFormat("Order by Description ")
        dt = dat.GetData(sql.ToString())
        'MyObj.WriteLog(sql.ToString())

        ddlControl.DataTextField = "Description"
        ddlControl.DataValueField = "Code"
        ddlControl.DataSource = dat.GetData(sql.ToString())
        ddlControl.DataBind()
        ddlControl.Items.Insert(0, MyObj.GetDDLPleaseChooseItem())

        Me.lblLevel2Name.Text = Me.Level2Name & "："
    End Sub
#End Region

#Region "方法"
    Public Sub InitDataAndShow()

        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim hmManager As New HierarchyManager
        Dim MySignature As String = Me.ddlSignature.SelectedValue
        If Me.ddlLevel2Name.SelectedValue <> "" Then
            MySignature = Left(MySignature, 2)
        End If

        'Search 條件
        sql.AppendFormat(" SELECT Distinct A.Division,'" & MySignature & "' as Signature,C.Description as Level1Name, D.Description as Level2Name ")
        If Me.IsChain = "Y" Then
            sql.AppendFormat(",D.Code as Level2Value ")
        Else
            sql.AppendFormat(",substring(D.Code,{0}*2-1,2) as Level2Value ", hmManager.GetSequence(Me.Level2Name))
        End If
        sql.AppendFormat(" ,A.Channel, A.ChannelName, (CAST( B.Percentage AS varchar(50))+'%') AS Percentage, B.Percentage AS iPercentage   ")
        sql.AppendFormat(" FROM ChannelView A LEFT JOIN ChannelPercentage B ")
        sql.AppendFormat(" ON A.[Signature] = Left(B.[Signature],2) AND A.Channel = B.Channel ")
        sql.AppendFormat(" AND B.Signature ='{0}' ", MySignature)
        If Me.ddlLevel2Name.SelectedValue <> "" Then
            sql.AppendFormat(" AND B.Level2Name='{0}' ", Me.Level2Name)
        Else
            sql.AppendFormat(" AND B.Level2Name='{0}' ", "")
        End If
        sql.AppendFormat(" AND B.Level2Value ='{0}' ", Me.ddlLevel2Name.SelectedValue)
        sql.AppendFormat(" LEFT JOIN  ProductHierarchyOriginal C ")
        sql.AppendFormat(" ON A.Signature = C.CODE AND C.LevelName='Signature' ")
        sql.AppendFormat(" LEFT JOIN  ProductHierarchyOriginal D ")
        sql.AppendFormat(" ON D.LevelName ='{0}' ", Me.Level2Name)
        sql.AppendFormat(" AND A.Signature = Left(D.CODE,2) ")
        If Me.IsChain = "Y" Then
            sql.AppendFormat(" AND D.CODE='{0}' ", Me.ddlLevel2Name.SelectedValue)
        Else
            sql.AppendFormat(" AND substring(D.code,{0}*2-1,2)='{1}' ", hmManager.GetSequence(Me.Level2Name), Me.ddlLevel2Name.SelectedValue)
        End If
        sql.AppendFormat(" WHERE 1=1 ")
        If ddlDivision.SelectedValue <> "" Then
            sql.AppendFormat(" AND A.Division='{0}' ", ddlDivision.SelectedValue)
        Else
            Dim dvManager As New DivisionManager
            sql.AppendFormat(" AND A.Division IN ({0}) ", MyObj.JoinFormat(",", "'{0}'", dvManager.GetDivisions()))
        End If

        If ddlSignature.SelectedValue <> "" Then
            sql.AppendFormat(" AND A.Signature ='{0}' ", Left(ddlSignature.SelectedValue, 2))
        Else
            Dim stManager As New SignatureManager
            sql.AppendFormat(" AND A.Signature IN ({0}) ", MyObj.JoinFormat(",", "'{0}'", stManager.GetSignatures(ddlDivision.SelectedValue)))
        End If

        sql.AppendFormat(" Order by A.Division, C.Description, A.ChannelName ")
        'MyObj.WriteLog(sql.ToString())
        Dim dt As DataTable = dat.GetData(sql.ToString())
        For i As Integer = 0 To dt.Rows.Count - 1
            dt.Rows(i)("Level1Name") = Me.ddlSignature.SelectedItem.Text
        Next
        Me.gv.Columns(2).HeaderText = Me.Level2Name

        Me.gv.DataSource = dt
        Me.gv.DataBind()

        ViewState("dtPercentage") = dt

    End Sub
#End Region

    Private Property IsChain() As String
        Get
            Return ViewState("IsChain")
        End Get
        Set(ByVal value As String)
            ViewState("IsChain") = value
        End Set
    End Property

    Private Property Level2Name() As String
        Get
            Return ViewState("Level2Name")
        End Get
        Set(ByVal value As String)
            ViewState("Level2Name") = value
        End Set
    End Property
End Class

